package dao

import "gorm.io/gorm"

type IUserRepo interface {
	GetUserById(id int) *User
	GetUserByUsername(username string) *User
	GetUserByEmail(email string) *User
	GetUserByPhone(phone string) *User
	CreateUser(user *User) error
	UpdateUser(user *User) error
	DeleteUser(user *User) error
	GetUserByUsernameAndPassword(username string, hashedPassword string) *User
	UserExists(field string, value interface{}) bool
	GetUsersByCondition(condition interface{}, arguments ...interface{}) []User
	GetUserByCondition(condition interface{}, arguments ...interface{}) *User
}

type UserRepo struct {
	db *gorm.DB
}

func NewUserRepo(db *gorm.DB) IUserRepo {
	return &UserRepo{db: db}
}

func (repo *UserRepo) GetUserById(id int) *User {
	var user User
	repo.db.Model(User{}).Find(&user, "id=?", id)
	return &user
}

func (repo *UserRepo) GetUserByUsername(username string) *User {
	var user User
	repo.db.Model(User{}).Find(&user, "name =?", username)
	return &user
}

func (repo *UserRepo) GetUserByEmail(email string) *User {
	var user User
	repo.db.Model(User{}).Find(&user, "email=?", email)
	return &user
}

func (repo *UserRepo) CreateUser(user *User) error {
	return repo.db.Create(user).Error
}

func (repo *UserRepo) UpdateUser(user *User) error {
	return repo.db.Save(user).Error
}

func (repo *UserRepo) DeleteUser(user *User) error {
	return repo.db.Delete(user).Error
}

func (repo *UserRepo) GetUserByUsernameAndPassword(username string, hashedPassword string) *User {
	var user User
	repo.db.Model(User{}).Where("username=? and password=?", username, hashedPassword).Find(&user)
	return &user
}

func (repo *UserRepo) UserExists(field string, value interface{}) bool {
	var user User
	repo.db.Model(User{}).Where(field+"=?", value).Find(&user)
	return user != (User{})
}

func (repo *UserRepo) GetUserByPhone(phone string) *User {
	var user User
	repo.db.Model(User{}).Where("phone = ?", phone).Find(&user)
	return &user
}

func (repo *UserRepo) GetUserByCondition(condition interface{}, argument ...interface{}) *User {
	var user User
	repo.db.Model(User{}).Where(condition, argument...).Find(&user)
	return &user
}

func (repo *UserRepo) GetUsersByCondition(condition interface{}, argument ...interface{}) []User {
	var user []User
	repo.db.Model(User{}).Where(condition, argument...).Find(&user)
	return user
}
